package com.tts.controller;

import com.tts.dto.LoginRequest;
import com.tts.dto.LoginResponse;  // 确保导入 LoginResponse
import com.tts.dto.RegisterRequest;
import com.tts.dto.UserInfoDTO;
import com.tts.entity.User;
import com.tts.service.AuthService;
import com.tts.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import com.tts.exception.BusinessException;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ResponseEntity<LoginResponse> login(@RequestBody LoginRequest request) {
        try {
            LoginResponse response = authService.login(request);  // 使用正确的 LoginResponse
            return ResponseEntity.ok(response);
        } catch (BusinessException e) {
            return ResponseEntity
                .status(HttpStatus.UNAUTHORIZED)
                .body(null);
        }
    }

    @PostMapping("/register")
    public ResponseEntity<Void> register(@RequestBody RegisterRequest request) {
        authService.register(request);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/info")
    public ResponseEntity<UserInfoDTO> getUserInfo() {
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        User user = userService.findByUsername(username);
        return ResponseEntity.ok(UserInfoDTO.fromUser(user));
    }
}